﻿ #region Disclaimer/Info
 
 /////////////////////////////////////////////////////////////////////////////////////////////////
 //
 //   File:		LoginController.cs
 //   Website:		http://dexterblogengine.com/
 //   Authors:		http://dexterblogengine.com/About.ashx
 //   Rev:		1
 //   Created:		19/01/2011
 //   Last edit:		19/01/2011
 //   License:		GNU Library General Public License (LGPL)
 //   File:            LoginController.cs
 //   For updated news and information please visit http://dexterblogengine.com/
 //   Dexter is hosted to Codeplex at http://dexterblogengine.codeplex.com
 //   For any question contact info@dexterblogengine.com
 //
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 
 #endregion

using System;
using System.Web.Mvc;
using System.Web.Security;
using Dexter.Logger.Contracts;
using Dexter.Services;
using Dexter.Web.Mvc.Filters;
using Dexter.Web.Mvc.ViewModel.Backoffice.Binders;
using Dexter.Web.Utils;

namespace Dexter.Web.Mvc.Controllers.Backoffice {
	[DexterCallFilter ( false )]
	public class LoginController : BackOfficeControllerBase {
		public LoginController ( IConfigurationService configurationService , IWebUtils webUtils , ILogger logger , IUrlBuilder urlBuilder , IContactService contactService ) : base ( configurationService , webUtils , logger , urlBuilder , contactService ) {}

		[AcceptVerbs ( HttpVerbs.Get )]
		public ActionResult Index ( ) {
			return View ( new CredentialLoginBinder {KeepLogged = true} );
		}

		[ValidateAntiForgeryToken]
		[AcceptVerbs ( HttpVerbs.Post )]
		public ActionResult Index ( CredentialLoginBinder credential ) {
			if ( credential == null || credential.Username.IsNullOrEmpty ( ) || credential.Password.IsNullOrEmpty ( ) ) {
				ModelState.AddModelError ( "_FORM" , "Wrong username or password." );
				return View ( new CredentialLoginBinder {KeepLogged = true} );
			}

			if ( !Membership.ValidateUser ( credential.Username , credential.Password ) ) {
				ModelState.AddModelError ( "_FORM" , "Wrong username or password." );
				return View ( credential );
			}

			FormsAuthentication.SetAuthCookie ( credential.Username , credential.KeepLogged );

			if ( !String.IsNullOrEmpty ( credential.ReturnUrl ) ) {
				return Redirect ( credential.ReturnUrl );
			}

			return RedirectToAction ( "Index" , "Home" , new {Area = ""} );
		}

		[AcceptVerbs ( HttpVerbs.Get )]
		public ActionResult LogOff ( ) {
			FormsAuthentication.SignOut ( );

			return RedirectToAction ( "Index" );
		}
	}
}
